import { asyncRouterMap, constantRoutes } from '@/router'
import { getAuthMenu } from '@/api/user'
import router from '@/router'

import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}


/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
 function generaMenu(routes, data) {
  
    data.forEach(item => {
       // http://a.com/a/order3
      // alert(JSON.stringify(item))
      const menu = {
        path: item.name ,
        component: item.children.length > 0 ? Layout : (resolve) => require([`@/views${item.name}/index`],resolve),
        // hidden: true,
        children: [],
        name: item.title,
        hidden: item.hidden==2?false:true,
        meta: { title: item.title, id: item.id, roles: ['admin'],icon: item.icon,}
      }
      if (item.children) {
        generaMenu(menu.children, item.children)
      }
      routes.push(menu)

    })
      return routes
  }
   

  

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes 
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit}) {
    console.log(this.getters.token)
    return new Promise(resolve => {
        
        // 先查询后台并返回左侧菜单数据并把数据添加到路由
        
        getAuthMenu(this.getters.token).then(response => {
          let {data,code} = response.data
         console.log(data,code)
          if (code == 404) {
            this.$message({
              message: '菜单数据加载异常',
              type: 0
            })
          } else {
           console.log(data)
           const loadMenuData = []
            // Object.assign(loadMenuData, data)
            
            let accessedRoutes=generaMenu(asyncRouterMap, data)
            
           
           
            accessedRoutes.push({ path: '*', redirect: '/404', hidden: true },{
                path: '/404',
                component: () => import('@/views/404'),
                hidden: false
              },)
            console.log(accessedRoutes)
            // router.options.routes = accessedRoutes
            router.addRoutes(accessedRoutes)
            
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
             
            console.log(router)
            // next({path: to.path})
          }
          // generaMenu(asyncRoutes, data)
        }).catch(error => {
          console.log(error)
        })
      })




  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
